<template>
  <div class="customer-info-record">
    <div class="customer-timeline" :style="inputState?'padding-bottom:170px;':'padding-bottom:70px;'" ref="timeline">
      <base-timeline 
        :data="recordPage.list" 
        :record-render="renderRecord" 
        :loading="recordLoading"
        :loadmore="recordPage.hasNextPage"
        @load="loadmore"/>
    </div>
    
    <div class="customer-quick-comment" v-if="editComment" :style="commentStyle">
      <!-- <base-comment ref="comment" @inputStateChange='inputStateChange' submit-text='提交' placeholder="请输入备注内容" @submit="createRemark" :disabled="commentPending" autofocus/> -->
      <biz-comment ref="comment" :placeholder="$t('customer.detail.customerInfoRecord.remarkPlaceholder')" @inputStateChange='inputStateChange' :submit-text="$t('common.base.submit')" @submit="createRemark" :disabled="commentPending" autofocus user-search-url="/message/user/lists" :search-params="{seeAllOrg:true}"></biz-comment>
    </div>
  </div>
</template>

<script>
import { isOpenData } from '@src/util/platform';
import { trimAll, formatDate, cutAtTextContent } from 'pub-bbx-utils';
import Page from '@model/Page';
import platform from '@src/platform';
import { useTenantId } from '@hooks/useRootWindow.ts';
import { t } from '@src/locales'
import { translateAction } from '@src/util/record'
/* mixin */
import { ConnectorModuleConnectorRecordMixin, ConnectorModuleTriggerRecordMixin } from '@src/modules/connector'

function createAttachmentDom(h, attachments){
  return attachments && attachments.length > 0 
    ? <div class="base-timeline-attachment base-file__preview">
      {attachments.map(item => <base-file-item Source={attachments} file={item} key={item.id} readonly size="small"/>)}
    </div> 
    : ''
}
function createLinkDom(h, s){
  const reg = /((((https?|ftp?):(?:\/\/)?)(?:[-;:&=\+\$]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\?\+=&;:%!\/@.\w_]*)#?(?:[-\+=&;%!\?\/@.\w_]*))?)/g;
  const str = s.replace(reg, str=>`@#@${str}@#@`);
  const arr = str.split('@#@');
  return <p class="pre-line secondary-info">{arr.map(item=>{
    if(item.indexOf('http') === 0){
      return <a href={item} target='_blank'>{item}</a>
    }
    return <biz-comment-html html={item}></biz-comment-html>
    
  })}</p>
}
export default {
  name: 'customer-info-record',
  mixins: [ConnectorModuleConnectorRecordMixin, ConnectorModuleTriggerRecordMixin],
  props: {
    shareData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      isOpenData,
      params: {
        primaryId: this.shareData.customer.id,
        pageNum: 1,
        pageSize: 15,
      },
      recordPage: new Page(),
      recordLoading: false,
      commentPending: false,
      inputState:false
    }
  },
  inject:['initData'],
  computed: {
    commentStyle(){
      if(this.shareData.collapseDirection == 'left'){
        return 'width:calc(100% - 205px);bottom:0px;'
      }else if(this.shareData.collapseDirection === ''){
        return 'width:calc(50% - 50px);bottom:0px;'
      }return 'width:calc(70% - 25px);max-width:calc(100% - 445px);bottom:0px;'
    },
    customer(){
      return this.shareData.customer || {};
    },
    // 客户ID
    customerId() {
      return this.shareData.customer ? this.shareData.customer.id : '';
    },
    // 客户姓名
    customerName(){
      return this.shareData.customer ? this.shareData.customer.name : '';
    },
    // 当前用户id
    loginUser(){
      return this.shareData.loginUser;
    },
    // 权限
    authorities(){
      let user = this.loginUser || {};
      return user.authorities || {};
    },
    /** 是否允许操作 */
    allowOperate(){
      return this.customer.isDelete === 0;
    },
    /** 编辑权限 */
    allowEditCustomer() {
      return this.shareData.allowEditCustomer;
    },
    /** 添加备注权限 */
    editComment(){
      return this.allowEditCustomer && this.allowOperate;
    },
  },
  methods: {
    inputStateChange(val){
      this.inputState = val;
    },
    /** 添加备注 */
    async createRemark(form){
      try{
        this.commentPending = true;
        let tenantId = useTenantId().value;
        let customer = this.customer
        let url = ''
        if(form.receivers){
          url = `?tenantId=${tenantId}&bizId=${customer.id}&sendUserName=${this.initData.loginUser.displayName}&receivers=${form.receivers}&templateId=${customer.templateId || ''}&templateName=${customer.templateName || ''}&bizNo=${customer.name}`
          url += `&content=${cutAtTextContent(form.originalContent)}`
        }
        let params = {
          primaryId: this.customerId,
          primaryName: this.customerName,
          attachments: form.attachments,
          showInOwn: form.showInOwn,
          content: {
            updateContent: form.content,
            updateType: 'ptRecord'
          }
        }
        let result = await this.$http.post(`/customer/createRemark${url}`, params);
        
        if(result.status == 0){
          this.$refs.comment.reset();
          await this.initializeRecord();
          this.$nextTick(() => {
            this.$refs.timeline.scrollTop = 0;
          })
        }else{
          platform.alert(result.message)
        }

        this.commentPending = false;
      }catch(e){
        console.error(e)
      }
    },
    renderAddressRecordDom({action, userName, showInOwn, content, staffId, userId}) {
      let address = trimAll(content.address);
      let icon = address ? <i class="iconfont icon-address"></i> : '';
      let str = '';
      let addressDom = <span class="icon-address-content" onClick={e => this.openMap(content)}>{icon}{address}</span>;
      if (content.type === '设为默认') {
        str = <i18n path="common.record.product.record1" tag="span">
            <template slot="addressDom">{addressDom}</template>
          </i18n>
      } else if (content.type === 'API设为默认') {
        str = <i18n path="common.record.product.record2" tag="span">
            <template slot="clientName">{content.clientName}</template>
            <template slot="addressDom">{addressDom}</template>
          </i18n>
      } else if (content.type === 'API添加') {
        str = <i18n path="common.record.product.record3" tag="span">
            <template slot="clientName">{content.clientName}</template>
            <template slot="addressDom">{addressDom}</template>
          </i18n>
      } else {
        str = <i18n path={`common.record.product.actionIsAddress['${content.type}']`} tag="span">
            <template slot="addressDom">{addressDom}</template>
          </i18n>
      }
      return (
        <h5>{this.renderUserName(userName, staffId, userId)}{str}。</h5>
      )
    },
    renderLinkmanRecordDom({action, userName, showInOwn, content, staffId, userId}) {
      let message = '';
      if (content.type === '设为默认') {
        message = this.$t('common.record.product.record5', { name: content.name });
      } else if (content.type === 'API设为默认') {
        message = this.$t('common.record.product.record6', { clientName: content.clientName, name: content.name });
      } else if (content.type === 'API添加') {
        message = this.$t('common.record.product.record7', { clientName: content.clientName, name: content.name });
      } else {
        message = this.$t(`common.record.product.actionIsLinkMan['${content.type}']`, {name: content.name });
      }

      return <h5>{this.renderUserName(userName, staffId, userId)}{message}。</h5>
    },
    renderProductRecordDom({action, userName, showInOwn, content, staffId, userId}) {
      const typeStr = translateAction(content.type)
      return <h5>{this.renderUserName(userName, staffId, userId)}{ `${typeStr}${t('common.form.type.product')}${content.name || ''}`}。</h5>
    },
    /** 根据记录的action渲染对应的内容，支持jsx和render函数 */
    renderRecord(h, item){
      let {action, userName, showInOwn, content, attachments, primaryName, staffId, userId} = item;
      
      if(action == '备注'){
        return [
          <h5 class="main-info">
            <i18n path="common.record.task.somebodyAddRemark" tag="span">
              <span place="operator">{this.renderUserName(userName, staffId, userId)}</span>
            </i18n>
            {!!showInOwn && (
              <span class="private">
                <i class="iconfont icon-account1"></i>{t('task.record.onlyVisibleToYourself')}
              </span>
            )}。
            {
              this.allowDeleteRecord(item) 
              && <el-button class="btn-text base-timeline-delete" onClick={e => this.deleteRemark(item)}>
                <i class="iconfont icon-shanchu"></i>{t('common.base.delete')}
              </el-button>
            }
          </h5>,
          content.isDelete == 'true'
            ? <i18n class="text-danger" path="common.record.task.somebodyDeleteRemark" tag="p">
                <span place="operator">{this.renderUserName(content.deleteUserName, content.deleteUserStaffId)}</span>
                <span place="time">{ formatDate(content.deleteTime) }</span>
              </i18n>
            : [createLinkDom(h, content.updateContent), createAttachmentDom(h, attachments)]
        ]
      }

      if(action == '地址') return this.renderAddressRecordDom(item);

      if(action == '联系人') return this.renderLinkmanRecordDom(item);
      if(action === '产品') return this.renderProductRecordDom(item);

      if(action == '消息提醒'){
        if(content.type == '已发送') {
          let info = [
            <h5>{this.$t('common.record.product.record13.text1')}</h5>, 
            <p>{this.$t('common.record.product.record13.text2')}：{content.remindName}</p>, 
            <p>{this.$t('common.record.product.record13.text3')}：{this.$t('common.record.product.record13.text4')}：{content.remindTo}</p>
          ]
          if(content.customerManagerName) info.push(
            <p class="principal-info">{this.$t('common.record.product.record13.text5')}：{this.renderUserName(content.customerManagerName, content.customerManagerStaffId)}</p>
          )
          if(content.customerManagerName === null) info.push(
            <p class="principal-info">{this.$t('common.record.product.record13.text5')}：{this.$t('common.record.product.record13.text6')}</p>
          );
          if(content.tagName) info.push(
            <p class="principal-info">{this.$t('common.record.product.record13.text7')}：{content.tagName}</p>
          );
          if(content.tagName === null) info.push(
            <p class="principal-info">{this.$t('common.record.product.record13.text7')}：{this.$t('common.record.product.record13.text8')}</p>
          );
          return info;
        }
        return [
          <h5>{this.renderUserName(userName, staffId, userId)}{this.$t(`common.record.product.record13['${content.type}']`)}</h5>,
          <p className="secondary-info">{this.$t('common.record.product.record13.text2')}：{content.remindName}</p>,
          content.rule ? <p class="secondary-info">{content.rule}</p> : ''
        ]
      }
      if(action === '发送短信'){
        if(content.type === '添加'){
          return [
            <h5>{this.renderUserName(userName, staffId, userId)}{this.$t('common.record.product.record14.text1', { templateName: content.templateName })}</h5>,
            <p class="secondary-info">{this.$t('common.record.product.record14.text2')}：{ formatDate(content.sendTime) }</p>,
            <p className="secondary-info">{this.$t('common.record.product.record14.text3')}：{content.remindToName}</p>
          ]
        }

        if(content.type === '已发送'){
          return [
            <h5>{this.$t('common.record.product.record14.text4', {templateName: content.templateName})}</h5>,
            <p className="secondary-info">{this.$t('common.record.product.record14.text3')}：{content.remindToName}</p>
          ]
        }
      }

      if(action === '批量更新') return [
        <h5>{this.renderUserName(userName, staffId, userId)}{this.$t('common.record.customer.updateByImport')}</h5>,
        content.updateFields ? <p class="secondary-info">{this.$t('common.record.product.record15.text2')}：{content.updateFields}</p> : '',
        // createAttachmentDom(h,attachments)
      ]

      if (action === 'API新建') return [
        <h5>{this.renderUserName(userName, staffId, userId)}{
          t('common.record.customer.createByApi', {
            clientName: content.clientName,
            primaryName
          })
          }</h5>,
      ]

      if (/工单/.test(action)) {
        const actionStr = item.action.indexOf('新建工单') > -1 ? item.action.indexOf('API') > -1 ? 'API新建' : '新建' : '完成'
        const str = this.$t(`common.record.customer.createTask['${actionStr}']`, {
          taskNo: content.taskNo,
          taskType: content.taskType
        });
        return (
          <h5>
            {this.renderUserName(userName, staffId, userId)}
            {str}
          </h5>
        )
      }

      if (/事件/.test(action)) {
        const actionStr = item.action.indexOf('新建事件') > -1 ? item.action.indexOf('API') > -1 ? 'API新建' : '新建' : '完成'
        const str = this.$t(`common.record.customer.createEvent['${actionStr}']`, {
          actionStr,
          eventNo: content.eventNo,
          taskType: content.taskType
        })
        return (
          <h5>
            {this.renderUserName(userName, staffId, userId)}
            {str}
          </h5>
        )
      }

      if (action === '新建计划') {
        const {planName, taskType, planTime, end} = content
        let str1 = this.$t('common.record.customer.createPlanTask', { planName, taskType, planTime: formatDate(planTime) });
        let str2 = content.time === 'times'
          ? this.$t('common.record.product.record20.text2', { end }) // 这是次数
          : `${this.$t('common.record.product.record20.text3')}：${ formatDate(end) }。`;

        return (
          <h5>{this.renderUserName(userName, staffId, userId)}{str1}{str2}</h5>
        )
      }

      if (action === '编辑计划') {
        let str = content.updateFields;
        if (str && /计划任务名称/.test(str)) {
          str = str.replace('计划任务名称', this.$t('common.record.product.record21.text1', {planName: content.newPlanName}));
        }
        return (
          <h5>
            {this.renderUserName(userName, staffId, userId)}{this.$t('common.record.customer.editPlanTask')}：{content.oldPlanName}。
            {str ? <p class="secondary-info">{this.$t('product.modifyField')}：{str}。</p> : ''}
          </h5>
        )
      }

      if (action === '合并客户') {
        const {oldCustomers, newCustomer, customerName, customerSn} = content
        let str1 = this.$t('common.record.customer.mergeCustomer', { oldCustomers, newCustomer });
        return (
          <h5>{this.renderUserName(userName, staffId, userId)}{str1}</h5>
        )
      }

      if(action == '关注'){
        return <i18n path="common.record.customer.attention" tag="h5">
          <span place="operator">{this.renderUserName(userName, staffId, userId)}</span>
        </i18n>
      }

      if(action == '取消关注'){
        return <i18n path="common.record.customer.cancelAttention" tag="h5">
          <span place="operator">{this.renderUserName(userName, staffId, userId)}</span>
        </i18n>
      }

      if(action == '被取消关注'){
        let userNameDetail = null
        let fmtUserName = content.namesList;
        let names = fmtUserName.split(',');

        if(names.length > 3){
          fmtUserName = names.reduce((acc, cur, index, arr) => {
            if(index > 3) return acc;
            if(index == 3) {
              return `${acc.slice(0, -1)}${t('common.record.customer.morePerson', {num:arr.length})}`;
            }

            return `${acc}${cur},`;
          }, '');

          if(fmtUserName.endsWith(',')) fmtUserName = fmtUserName.slice(0, -1);

          userNameDetail = <p>{content.namesList}</p>
        }

        return [
          <i18n path="common.record.customer.cancelAttention2" tag="h5">
            <span place="operator">{this.renderUserName(userName, staffId, userId)}</span>
            <strong place="customer">{fmtUserName}</strong>
          </i18n>,
          userNameDetail
        ]
      }

      if(action == '电话日志'){
        return <i18n path="common.record.task.phoneLog" tag="h5">
          <span place="operator">{this.renderUserName(userName, staffId, userId)}</span>
          <strong place="targetName">{content.targetName}</strong>
        </i18n>
      }

      if(action == '卡片'){
        return <i18n path={`common.record.task.taskCard['${content.action}']`} tag="div">
          <span place="userName">{this.renderUserName(userName, staffId, userId)}</span>
          <span place="cardName">{ content.cardName }</span>
        </i18n>
      }
      
      // 呼入接听、呼入未接听、呼出接听、呼出未接听
      if(item.module == 'callCenter' && action == '通话结束') {
        if(content.isDealing === 'true') {
          return <i18n tag="h5" path={ content.isCallIn === 'true' ? 'common.record.acceptPhone' : 'common.record.callPhone'}>
            <strong place="userName">{content.agentName}</strong>
            <strong place="targetName">{content.linkmanName}</strong>
          </i18n>
        } 
        if(content.isCallIn === 'true') {
          return <i18n path="common.record.somebodyPhoneIsNoAnswer" tag="h5">
            <strong place="userName">{content.linkmanName}</strong>
          </i18n>
        } 
        return <i18n path="common.record.somebodyPhoneIsNoAnswer2" tag="h5">
            <strong place="userName">{content.agentName}</strong>
            <strong place="targetName">{content.linkmanName}</strong>
          </i18n>
      }

      if(action == '修改标签') return this.renderCustomerTagRecordDom(item);
      if(action == '关联') return this.renderRelationLinkmanRecordDom(item);
      if(action == '发送活动') return this.renderActivityRecordDom(item);
      if(action == '发送邮件') return this.renderEmailRecordDom(item);
      if (action === '连接器to') return this.renderConnectorTo(item)
      if (action === '连接器from') return this.renderConnectorFrom(item)
      if (action === '触发器to') return this.renderTriggerTo(item)
      if (action === '触发器from') return this.renderTriggerFrom(item)
      if (action === '坐席呼出' || action === '客户呼入') return this.renderCallCenterRecord(item)
      // 根据后端返回action做翻译枚举
      const actionDes = translateAction(action)
      return [
        <i18n path="common.record.customer.normal" tag="h5">
          <span place="operator">
            {this.renderUserName(userName, staffId, userId)}
          </span>
          <span place="action">
            {actionDes}
          </span>
        </i18n>,
        content.updateFields ? <p class="secondary-info">{this.$t('product.modifyField')}：{content.updateFields}</p> : '',
        createAttachmentDom(h, attachments)
      ];
    },
    openMap(content){
      let longitude = content.longitude;
      let latitude = content.latitude;

      if(!longitude || !latitude) return;
      
      this.$fast.map.display({ ...content })
        .catch(err => console.error('openMap catch an err: ', err));
    },
    /** 
     * 同时满足以下条件允许删除该记录
     * 1. 该记录没有被删除
     * 2. 客户编辑权限（CUSTOMER_EDIT）值为3 或者 是创建人
     * 3. 该客户没有被删除
     */
    allowDeleteRecord(item){
      let isDelete = item.content.isDelete == 'true';
      let authorities = this.authorities
      let user = this.loginUser;
      let isCreator = item.userId == user.userId;

      return !isDelete && ((authorities['CUSTOMER_EDIT'] && authorities['CUSTOMER_EDIT'] == 3) || isCreator) && this.allowOperate;
    },
    /** 初始化信息动态 */
    async initializeRecord() {
      this.params.pageNum = 1;
      this.searchRecord();
    },
    /** 加载下一页 */
    async loadmore() {
      try {
        this.params.pageNum++;
        this.recordLoading = true;
        let result = await this.fetchRecord(this.params);
        this.recordLoading = false;
        this.recordPage.merge(result)
      } catch (error) {
        console.error(error)
      }
    },
    /** 抓取信息动态 */
    fetchRecord(params){
      return this.$http.get('/customer/cRecord', params);
    },
    /** 删除备注 */
    async deleteRemark(record) {
      try {
        if (!await this.$platform.confirm('确认删除该备注吗？')) return;
        const delRes = await this.$http.post('/customer/deleteCustomerRecord', {id: record.id}, false);
        if(delRes.status == 0) this.initializeRecord();
      } catch (e) {
        console.error('deleteMark catch err', e);
      }
    },
    async searchRecord() {
      try {
        this.recordLoading = true;
        let result = await this.fetchRecord(this.params);
        this.recordLoading = false;
        this.recordPage.list = [];
        this.recordPage.merge(result)
      } catch (error) {
        console.error(error)
      }
    },
    renderCustomerTagRecordDom(record = {}) {
      let { action, userName, content = {}, staffId, userId } = record
      let deleteTagsString = content?.del || ''
      let addTagsString = content?.add || ''
      
      return (
        <div>
          <i18n path="common.record.customer.customerTagRecord" tag="h5">
            <strong place="operator">{this.renderUserName(userName, staffId, userId)}</strong>
          </i18n>
          {deleteTagsString && (
            <div calss="customer-record-tag-delete-text">{t('common.record.customer.deleteLabel', {deleteTagsString})}</div>
          )}
          {addTagsString && (
            <div>{t('common.record.customer.addLabel', {addTagsString})}</div>
          )}
        </div>
      )
    },
    renderRelationLinkmanRecordDom(record = {}) {
      let { userName, content = {}, staffId, userId } = record
      let linkman = content?.linkman || ''
      
      return (
        <div>
          <i18n path="common.record.customer.relationLinkmanRecord" tag="h5">
            <span place="operator">{this.renderUserName(userName, staffId, userId)}</span>
            <span place="linkman">{linkman}</span>
          </i18n>
        </div>
      )
    },
    renderUserName(userName, staffId, userId){
      return (
        <recordUserName userName={userName} staffId={staffId} userId={userId} />
      )
    },
    renderActivityRecordDom(record = {}) {
      let { userName, content = {}, staffId } = record;
      let actionStr = '';
      const smsTemplateName = content?.smsTemplateName ? this.$t('common.record.product.record23.text1', {smsTemplateName: content.smsTemplateName}) : '';
      const activitiesName = content?.activitiesName ? `【${content.activitiesName}】` : '';
      if(content.isSendEmail === '1' && content.isSendSms === '0') {
        actionStr = this.$t('common.record.product.record23.text2', {activitiesName});
      }
      if(content.isSendSms === '1' && content.isSendEmail === '0') {
        actionStr = this.$t('common.record.product.record23.text3', {smsTemplateName, activitiesName});
      }
      if(content.isSendEmail === '1' && content.isSendSms === '1') {
        actionStr = this.$t('common.record.product.record23.text4', {smsTemplateName, activitiesName});
      }
      return (<h5>{this.renderUserName(userName, staffId)}{actionStr}</h5>);
    },
    renderEmailRecordDom(record = {}) {
      let { userName, staffId } = record;
      return [
      <h5>{this.renderUserName(userName, staffId)}{this.$t('common.record.product.record24')}</h5>
      ]
    },
    // 渲染呼叫中心呼叫动态
    renderCallCenterRecord(record = {}) {
      return (
        <biz-call-center-record record={record} />
      )
    },
  },
  mounted() {
    this.initializeRecord();
    this.$eventBus.$on('customer_info_record.update_record_list', this.searchRecord);
  },
  beforeDestroy() {
    this.$eventBus.$off('customer_info_record.update_record_list', this.searchRecord);
  }
}
</script>

<style lang="scss">
.icon-address-content{
  cursor: pointer;
}
.icon-address-content:hover{
    color:$color-primary-light-6
 }
.customer-info-record {
  
  height: 100%;
  display: flex;
  flex-flow: column nowrap;

  h5 {
    margin-bottom: 5px;
    .icon-address {
      margin-left: 5px;
    }
  }

  .private {
    @include fontColor();
    .iconfont {
      font-size: 14px;
      margin: 0 6px;
    }
  }

  .secondary-info {
    margin-top: 8px;
  }

  .error-info {
    color: #E51C23;
  }

}

.customer-timeline{
  padding-top: 15px;
  flex: 1;
  // overflow: auto;
  padding-right: 15px;
  // margin-bottom: 150px;
}

p.principal-info {
  margin-left: 70px;
}

.customer-record-tag-delete-text {
  color: $color-danger;
}
</style>
